﻿using System;
using System.Security.Cryptography;
using System.Text;
using Framework.DataAccess;
using Project.Domain.Entities;
using Framework.Util.Cryptography;
using Project.Payment.Liberty;

namespace Project.DAL.Repository
{
    public interface IUserService : IRepository<User>
    {               
        bool ComparePassWord(string passInto, string username);
        bool CompareUsername(string username);        
        bool CheckEmail(string email);
        bool CheckAccountLr(string lrString);
        string ForgotPass();
        string EncryptSha256(string stringTo);
    }

    public class UserService :RepositoryBase<User>, IUserService
    {        
        public UserService(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
        {

        }

        public bool ComparePassWord(string passInto, string username)
        {            
            var user = Get(u => u.UserName.Equals(username));
            var passget = CryptographyManager.Decrypt(user.Password);
            return passInto.Equals(passget);
        }

        public bool CompareUsername(string username)
        {
            var user = Get(u => u.UserName.Equals(username));
            return user != null;
        }

        public bool CheckAccountLr(string lrString)
        {
            var user = Get(u => u.LrAccount.Equals(lrString));
            if (user != null)
            {
                return false;
            }

            var accountname = new AccountName();
            var name = accountname.CheckAccountName(lrString);
            return !name.Equals("false");
        }

        public string ForgotPass()
        {
            const string allowedChars = "<,?,>,:,',-,`,+*,$,#,~,@,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,g,h,k,l,m,o,p,q,r,s,t,u";
            char[] sep = { ',' };
            var arr = allowedChars.Split(sep);

            var passwordString = "";

            var rand = new Random();
            for (var i = 0; i < 8; i++)
            {
                var temp = arr[rand.Next(0, arr.Length)];
                passwordString += temp;
            }
            return passwordString;
        }

        public string EncryptSha256(string stringTo)
        {
            var ue = new UTF8Encoding();
            var messageBytes = ue.GetBytes(stringTo);
            var sHhash = new SHA256Managed();
            var strHex = "";
            var hashValue = sHhash.ComputeHash(messageBytes);
            foreach (var b in hashValue)
            {
                strHex += String.Format("{0:X2}", b);
            }
            return strHex;
        }                      

        public bool CheckEmail(string email)
        {
            var userEntity = Get(u => u.Email.Equals(email));
            return userEntity != null;
        }
    }
}